﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MaxAlarm.Common;
using MaxAlarm.Common.Data;

namespace MaxAlarm.Windows
{
    /// <summary>
    /// Interaction logic for AlarmWindow.xaml
    /// </summary>
    public partial class AlarmWindow : Window
    {
        public static readonly DependencyProperty AlarmItemsProperty =
            DependencyProperty.Register("AlarmItems", typeof(ObservableCollection<AlarmItem>), typeof(AlarmWindow), new PropertyMetadata(null, ItemsChanged));

        private static void ItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var window = (AlarmWindow)d;

            window.GroupedItems = window.AlarmItems.GroupBy(ex => ex.AlarmType).ToDictionary(ex => ex.Key,
                                                                                             ex => ex.ToList().Count);
        }

        public ObservableCollection<AlarmItem> AlarmItems
        {
            get { return (ObservableCollection<AlarmItem>)GetValue(AlarmItemsProperty); }
            set { SetValue(AlarmItemsProperty, value); }
        }

        public static readonly DependencyProperty GroupedItemsProperty =
            DependencyProperty.Register("GroupedItems", typeof (Dictionary<string, int>), typeof (AlarmWindow));

        public Dictionary<string, int> GroupedItems
        {
            get { return (Dictionary<string, int>) GetValue(GroupedItemsProperty); }
            set { SetValue(GroupedItemsProperty, value); }
        }

        public AlarmWindow()
        {
            AlarmItems = new ObservableCollection<AlarmItem>();
            InitializeComponent();
            DataContext = this;
            WindowStartupLocation = WindowStartupLocation.Manual;
            Left = SystemParameters.WorkArea.Right - Width - 2;
            Top = SystemParameters.WorkArea.Bottom - Height - 2;
        }

        private void CloseWindow(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            if(Owner != null)
                Owner.StateChanged += delegate 
                { 
                    WindowState = WindowState.Normal;
                    Show();
                    Activate();
                };
        }
    }
}
